#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "options.h"

#define FLAG_A 0x01 //simple switch
#define FLAG_C 0x02 //simple switch
#define FLAG_R 0x04 //switch with argument
#define FLAG_X 0x08 //switch with argument
#define FLAG_Z 0x10 //simple switch

#define BUFFER 256

const char *ERROR_MESSAGE = "USAGE optionTest FILE [-a -c -r ARG_R -x ARG_X -z]";
void optionError(void);

int main(int argc, char **argv){
    int mask = 0x00;
    char *temp;
    char *file_name;

    //option arguments
    char *arg_r, *arg_x;
    char option;
    int arg_index;

   arg_index = 1;

   file_name = (char *)malloc(BUFFER);
   if(file_name != NULL) {
	if (argv[arg_index][0] == '-')
	    optionError();
	file_name = argv[arg_index++];
   }else
       exit(EXIT_FAILURE);

   while(arg_index < argc){
	//getOption will allocate memory for temp
	option = getOption(argv, argc, arg_index, &temp);
	switch(option){
	    case 'a':
			mask |= FLAG_A;
			arg_index++;
		break;
	    case 'c':
			mask |= FLAG_C;
			arg_index++;
			break;
	    case 'r':
			mask |= FLAG_R;
			if(temp != NULL)
				arg_r = temp;
			else
			   optionError();
			arg_index+=2;
		break;
	    case 'x':
			mask |= FLAG_X;
			if(temp != NULL)
				 arg_x = temp;
			else
				optionError();
			arg_index+=2;
			break;
	    case 'z':
			mask |= FLAG_Z;
			arg_index++;
			break;
	    default:
			optionError();
			exit(EXIT_FAILURE);
			break;
	}
}

    if( (mask & FLAG_A) == FLAG_A)
		printf("Flag a toggled\n");
    if( (mask & FLAG_C) == FLAG_C)
		printf("Flag c toggled\n");
    if( (mask & FLAG_R) == FLAG_R)
		printf("Flag r toggled with argument %s\n", arg_r);
    if( (mask & FLAG_X) == FLAG_X)
		printf("Flag x toggled with argument %s\n", arg_x);
    if( (mask & FLAG_Z) == FLAG_Z)
		printf("Flag x toggled\n");

	{
		int i = 0;
		scanf("%d", i);
	}
    exit(EXIT_SUCCESS);
}

void optionError(void){
    printf("%s\n", ERROR_MESSAGE);
    exit(EXIT_FAILURE);
}
